<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>渐进式脑波数据测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status.warming {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }
        .progress-fill {
            height: 100%;
            background-color: #007bff;
            transition: width 0.3s ease;
        }
        .data-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        .data-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            border-left: 4px solid #007bff;
        }
        .data-card h3 {
            margin: 0 0 10px 0;
            color: #495057;
            font-size: 14px;
        }
        .data-value {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
        }
        .brain-state {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .brain-state h2 {
            margin: 0 0 15px 0;
            color: white;
            font-size: 1.2em;
        }
        
        .brain-state-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-top: 10px;
        }
        
        .brain-state-item {
            background: rgba(255, 255, 255, 0.1);
            padding: 10px;
            border-radius: 5px;
        }
        
        .brain-state-item .label {
            font-weight: bold;
            display: block;
            margin-bottom: 5px;
        }
        
        /* 信号状态样式 */
        .signal-excellent { color: #28a745; font-weight: bold; }
        .signal-good { color: #28a745; }
        .signal-fair { color: #ffc107; }
        .signal-poor { color: #fd7e14; }
        .signal-very_poor { color: #dc3545; font-weight: bold; }
        .signal-no_signal { color: #dc3545; font-weight: bold; animation: blink 1s infinite; }
        
        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0.5; }
        }
        
        /* 连接状态样式 */
        #connectionStatus {
            padding: 15px;
            border-radius: 8px;
            margin: 10px 0;
            border: 2px solid;
        }
        
        #connectionStatus.connected {
            background-color: #d4edda;
            border-color: #28a745;
            color: #155724;
        }
        
        #connectionStatus.disconnected {
            background-color: #f8d7da;
            border-color: #dc3545;
            color: #721c24;
        }
        
        /* 警告消息样式 */
        .warning-message {
            background-color: #fff3cd;
            border: 2px solid #ffc107;
            color: #856404;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.02); }
            100% { transform: scale(1); }
        }
        
        .warning-message strong {
            display: block;
            margin-bottom: 8px;
            font-size: 1.1em;
        }
        .confidence {
            font-size: 18px;
            margin: 10px 0;
        }
        .controls {
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        .btn-primary:hover {
            background-color: #0056b3;
        }
        .btn-danger:hover {
            background-color: #c82333;
        }
        .log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            height: 200px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>渐进式脑波数据测试</h1>
        
        <div class="controls">
            <input type="text" id="devicePort" placeholder="设备端口 (可选, 如COM3)" style="padding: 8px; margin-right: 10px;">
            <input type="text" id="roomId" placeholder="房间ID (可选)" style="padding: 8px; margin-right: 10px;">
            <button class="btn-primary" onclick="connectDevice()">连接设备</button>
            <button class="btn-danger" onclick="disconnectDevice()">断开设备</button>
            <button class="btn-primary" onclick="connect()">连接WebSocket</button>
            <button class="btn-danger" onclick="disconnect()">断开连接</button>
            <button class="btn-primary" onclick="clearLog()">清空日志</button>
        </div>
        
        <div id="connectionStatus" class="status disconnected">未连接</div>
        
        <div id="warmupSection" style="display: none;">
            <h3>预热进度</h3>
            <div class="progress-bar">
                <div id="progressFill" class="progress-fill" style="width: 0%"></div>
            </div>
            <div id="warmupInfo">等待开始...</div>
        </div>
        
        <div class="data-grid">
            <div class="data-card">
                <h3>Delta波段</h3>
                <div id="deltaValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>Theta波段</h3>
                <div id="thetaValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>Alpha波段</h3>
                <div id="alphaValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>Beta波段</h3>
                <div id="betaValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>Gamma波段</h3>
                <div id="gammaValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>信号质量</h3>
                <div id="signalValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>信号状态</h3>
                <div id="signalStatus" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>注意力</h3>
                <div id="attentionValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>冥想度</h3>
                <div id="meditationValue" class="data-value">--</div>
            </div>
            <div class="data-card">
                <h3>会话信息</h3>
                <div>会话ID: <span id="sessionInfo">--</span></div>
                <div>房间ID: <span id="roomInfo">--</span></div>
                <div>时间戳: <span id="timestamp">--</span></div>
            </div>
        </div>
        
        <div id="connectionStatus" class="status">
             <h3>设备连接状态</h3>
             <div>等待连接...</div>
         </div>
         
         <div id="autoDisconnectWarning" class="warning-message" style="display: none;">
             <strong>⚠️ 自动断开警告</strong>
             <div id="warningMessage">--</div>
         </div>
        
        <div id="brainStateSection" style="display: none;">
            <div class="brain-state">
                <h2>脑状态分析</h2>
                <div>状态: <span id="brainState">--</span></div>
                <div class="confidence">置信度: <span id="confidence">--</span></div>
                <div>详细信息: <span id="details">--</span></div>
            </div>
        </div>
        
        <div class="log" id="logArea"></div>
    </div>
    
    <script>
        let websocket = null;
        let sessionId = null;
        
        // 连接设备
        async function connectDevice() {
            const devicePortInput = document.getElementById('devicePort');
            const roomIdInput = document.getElementById('roomId');
            const devicePort = devicePortInput.value.trim();
            const roomId = roomIdInput.value.trim();
            
            try {
                const requestBody = {};
                if (devicePort) {
                    requestBody.port = devicePort;
                }
                if (roomId) {
                    requestBody.room_id = roomId;
                }
                
                log(`连接设备请求: ${JSON.stringify(requestBody)}`);
                
                const response = await fetch('http://localhost:8000/api/device/connect', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    sessionId = result.session_id;
                    log(`设备连接成功! 会话ID: ${sessionId}, 房间ID: ${result.room_id}`);
                    document.getElementById('sessionInfo').textContent = sessionId;
                    document.getElementById('roomInfo').textContent = result.room_id;
                } else {
                    log(`设备连接失败: ${result.message}`);
                }
            } catch (error) {
                log(`设备连接错误: ${error.message}`);
            }
        }
        
        // 断开设备
        async function disconnectDevice() {
            if (!sessionId) {
                log('没有活动的会话');
                return;
            }
            
            try {
                const response = await fetch(`http://localhost:8000/api/device/disconnect/${sessionId}`, {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    log(`设备断开成功: ${result.message}`);
                    sessionId = null;
                    document.getElementById('sessionInfo').textContent = '--';
                    document.getElementById('roomInfo').textContent = '--';
                } else {
                    log(`设备断开失败: ${result.message}`);
                }
            } catch (error) {
                log(`设备断开错误: ${error.message}`);
            }
        }
        
        function connect() {
            if (!sessionId) {
                log('请先连接设备获取会话ID');
                return;
            }
            
            if (websocket) {
                websocket.close();
            }
            
            let wsUrl = `ws://localhost:8000/ws/progressive_data/${sessionId}`;
            log(`连接到: ${wsUrl}`);
            
            websocket = new WebSocket(wsUrl);
            
            websocket.onopen = function(event) {
                log('WebSocket连接已建立');
                updateConnectionStatus('connected', '已连接');
                document.getElementById('warmupSection').style.display = 'block';
            };
            
            websocket.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    handleMessage(data);
                } catch (e) {
                    log('解析消息失败: ' + e.message);
                }
            };
            
            websocket.onclose = function(event) {
                log('WebSocket连接已关闭');
                updateConnectionStatus('disconnected', '未连接');
                document.getElementById('warmupSection').style.display = 'none';
                document.getElementById('brainStateSection').style.display = 'none';
            };
            
            websocket.onerror = function(error) {
                log('WebSocket错误: ' + error);
                updateConnectionStatus('disconnected', '连接错误');
            };
        }
        
        function disconnect() {
            if (websocket) {
                websocket.close();
                websocket = null;
            }
        }
        
        function handleMessage(data) {
            log(`收到数据: ${JSON.stringify(data, null, 2)}`);
            
            // 更新会话信息
            if (data.session_id) {
                document.getElementById('sessionInfo').textContent = data.session_id;
            }
            if (data.room_id) {
                document.getElementById('roomInfo').textContent = data.room_id;
            }
            if (data.timestamp) {
                document.getElementById('timestamp').textContent = new Date(data.timestamp).toLocaleTimeString();
            }
            
            // 更新预热进度
            if (data.warmup_progress) {
                updateWarmupProgress(data.warmup_progress);
            }
            
            // 更新波段数据
            if (data.wave_data) {
                updateWaveData(data.wave_data);
            }
            
            // 更新连接状态
            if (data.connection_status) {
                updateConnectionStatusData(data.connection_status);
            }
            
            // 处理自动断开警告
            if (data.auto_disconnect_warning) {
                handleAutoDisconnectWarning(data.auto_disconnect_warning);
            } else {
                document.getElementById('autoDisconnectWarning').style.display = 'none';
            }
            
            // 更新脑状态分析
            if (data.brain_state) {
                updateBrainState(data.brain_state);
            }
            
            // 显示错误信息
            if (data.error) {
                log(`错误: ${data.error}`);
            }
            
            if (data.analysis_error) {
                log(`分析错误: ${data.analysis_error}`);
            }
        }
        
        function updateWarmupProgress(progress) {
            const progressFill = document.getElementById('progressFill');
            const warmupInfo = document.getElementById('warmupInfo');
            
            progressFill.style.width = progress.percentage + '%';
            warmupInfo.textContent = progress.message;
            
            if (progress.status === 'warming_up') {
                updateConnectionStatus('warming', `预热中 (${progress.percentage.toFixed(1)}%)`);
            } else if (progress.status === 'completed') {
                updateConnectionStatus('connected', '预热完成，正在分析');
            }
        }
        
        function updateWaveData(waveData) {
            document.getElementById('deltaValue').textContent = waveData.delta.toFixed(4);
            document.getElementById('thetaValue').textContent = waveData.theta.toFixed(4);
            document.getElementById('alphaValue').textContent = waveData.alpha.toFixed(4);
            document.getElementById('betaValue').textContent = waveData.beta.toFixed(4);
            document.getElementById('gammaValue').textContent = waveData.gamma.toFixed(4);
            document.getElementById('signalValue').textContent = waveData.poor_signal;
            document.getElementById('attentionValue').textContent = waveData.attention;
            document.getElementById('meditationValue').textContent = waveData.meditation;
            
            // 更新信号状态
            if (waveData.signal_status) {
                const signalStatus = waveData.signal_status;
                const statusElement = document.getElementById('signalStatus');
                statusElement.textContent = signalStatus.description;
                statusElement.style.color = signalStatus.color;
                statusElement.className = `data-value signal-${signalStatus.status}`;
            }
        }
        
        function updateConnectionStatusData(connectionStatus) {
            const statusSection = document.getElementById('connectionStatus');
            
            if (connectionStatus.connected) {
                statusSection.className = 'status connected';
                statusSection.innerHTML = `
                    <h3>✅ 设备已连接</h3>
                    <div>信号质量: ${connectionStatus.signal_quality.description}</div>
                `;
            } else {
                statusSection.className = 'status disconnected';
                statusSection.innerHTML = `
                    <h3>❌ 设备连接异常</h3>
                    <div>状态: ${connectionStatus.status || '未知'}</div>
                    <div>描述: ${connectionStatus.description || connectionStatus.signal_quality?.description || '无信号'}</div>
                `;
            }
        }
        
        function handleAutoDisconnectWarning(warning) {
            const warningElement = document.getElementById('autoDisconnectWarning');
            const messageElement = document.getElementById('warningMessage');
            
            warningElement.style.display = 'block';
            messageElement.textContent = warning.message;
            
            // 可以在这里添加自动断开逻辑
            console.warn('自动断开警告:', warning);
        }
        
        function updateBrainState(brainState) {
            document.getElementById('brainStateSection').style.display = 'block';
            document.getElementById('brainState').textContent = brainState.state;
            document.getElementById('confidence').textContent = (brainState.confidence * 100).toFixed(1) + '%';
            document.getElementById('details').textContent = JSON.stringify(brainState.details);
        }
        
        function updateConnectionStatus(type, message) {
            const statusElement = document.getElementById('connectionStatus');
            statusElement.className = `status ${type}`;
            statusElement.textContent = message;
        }
        
        function log(message) {
            const logArea = document.getElementById('logArea');
            const timestamp = new Date().toLocaleTimeString();
            logArea.innerHTML += `[${timestamp}] ${message}\n`;
            logArea.scrollTop = logArea.scrollHeight;
        }
        
        function clearLog() {
            document.getElementById('logArea').innerHTML = '';
        }
    </script>
</body>
</html>